#!/bin/bash  -e

function info() {
echo Usage: `basename $0` '[-n(ame) -c(pu) -m(em)] [-i cmd_opts_list]' cmd_next list_next cmd_monitor list_monitor
exit 65
}

while getopts  "n:m:c:i:p:h" opts
do
        case  $opts  in
		n) name=$OPTARG;;
		c) cpu=$OPTARG;;
		m) mem=$OPTARG;;
        i) cmd_opts_list=$OPTARG;;
		p) out_prefix=$OPTARG;;
		h) echo subq.sh -F -p1 -m1 monitors.sh -nsort -c2 -m2 "\"'sam2b_samtools.sh -t2'\"" 1.sam.list aln_bwa_bt.sh 1.cut.list; info;;
		*) info;;
        esac
done
shift $(($OPTIND - 1))


if [ $# -lt 4 ]; then info; fi

. /mnt/ilustre/app/medical/tools/.var

pid=.pid.log

s_start=`date +%s`

cmd=$3
list=$4
cmd_next=$1
list_next=$2

num_file=$cmd.nums.txt


nums=`seq $(wc -l $list|cut -f1 -d' ')|tee $num_file`

while true; do


	# i for identify the num of file list and list_next
	for i in $nums; do
		
		item=`sed -n "${i}"p $list`
		# echo;echo "$item"
		
		if 
		cat $pid |grep -F "$cmd"|grep -F "$item"|grep done # dot or other metacharactor will not be interpret
		then
		
			item_next=`sed -n ${i}p $list_next`
			echo; echo run item $i "$item_next" in $list_next; echo
			
			if test -z "$cmd_opts_list"; then 
				sub -w16 -F -n$name.$i -m$mem -p$cpu "$cmd_next" -p$out_prefix.$i "$item_next"
			else
				cmd_opts=`sed -n ${i}p $cmd_opts_list`
				sub -w16 -F -n$name.$i -m$mem -p$cpu "$cmd_next" $cmd_opts -p$out_prefix.$i "$item_next"
			fi
			
			# complementary
			echo $i|cat $num_file -|sort -n|uniq -u > tmp.$num_file # can not directly to > $num_file
			rm $num_file && mv tmp.$num_file $num_file
			
			nums=`cat $num_file`
		else

			echo item $i $cmd $item undone
		fi
		
		
	done
	
	s_end=`date +%s`
	sh=`awk 'BEGIN{printf("%.1f", ("'$s_end'"-"'$s_start'")/60/60)}'`
	sh0=`awk 'BEGIN{printf("%d", "'$sh'")}'`
	echo time pass $sh h.
	
	if test -z "$nums"; then
		break
	elif test $sh0 -gt 150; then
		break
	
	fi
	
	
	sleep 30
	
	
done
	
. $cmd_done